<?php declare(strict_types=1);

/**
 * @package Polls (Light Portal)
 * @link https://custom.simplemachines.org/index.php?mod=4244
 * @author Bugo <bugo@dragomano.ru>
 * @copyright 2021-2025 Bugo
 * @license https://spdx.org/licenses/GPL-3.0-or-later.html GPL-3.0-or-later
 *
 * @category plugin
 * @version 17.10.25
 */

namespace LightPortal\Plugins\Polls;

use Bugo\Compat\Config;
use Bugo\Compat\Lang;
use Bugo\Compat\Utils;
use LightPortal\Enums\Tab;
use LightPortal\Plugins\Event;
use LightPortal\Plugins\PluginAttribute;
use LightPortal\Plugins\SsiBlock;
use LightPortal\UI\Fields\InputField;
use LightPortal\UI\Fields\SelectField;
use LightPortal\Utils\Str;

if (! defined('LP_NAME'))
	die('No direct access...');

#[PluginAttribute(icon: 'fas fa-poll')]
class Polls extends SsiBlock
{
	public function prepareBlockParams(Event $e): void
	{
		$e->args->params['selected_item'] = 0;
	}

	public function validateBlockParams(Event $e): void
	{
		$e->args->params['selected_item'] = FILTER_VALIDATE_INT;
	}

	public function prepareBlockFields(Event $e): void
	{
		$polls = $this->getAll();

		if (empty($polls)) {
			InputField::make('selected_item', $this->txt['selected_item'])
				->setType('input')
				->setTab(Tab::CONTENT)
				->setDescription($this->txt['no_items'])
				->setAttribute('disabled', true);
		} else {
			SelectField::make('selected_item', $this->txt['selected_item'])
				->setTab(Tab::CONTENT)
				->setOptions($polls)
				->setValue($e->args->options['selected_item']);
		}
	}

	public function prepareContent(Event $e): void
	{
		$poll = $this->getFromSSI(
			'showPoll',
			Str::typed('int', $e->args->parameters['selected_item']),
			'array'
		);

		if (! $poll) {
			echo $this->txt['no_items'];
			return;
		}

		if ($poll['allow_vote']) {
			$form = Str::html('form', [
				'action' => Config::$boardurl . '/SSI.php?ssi_function=pollVote',
				'method' => 'post',
				'accept-charset' => Utils::$context['character_set'],
			]);

			$form->addHtml(Str::html('strong')->setText($poll['question']))->addHtml('<br>');

			if (! empty($poll['allowed_warning'])) {
				$form->addHtml($poll['allowed_warning'] . '<br>');
			}

			foreach ($poll['options'] as $option) {
				$label = Str::html('label', ['for' => $option['id']])
					->addHtml($option['vote_button'] . ' ' . $option['option']);

				$form->addHtml($label)->addHtml('<br>');
			}

			$form->addHtml(Str::html('input', [
				'type'  => 'submit',
				'value' => Lang::$txt['poll_vote'],
				'class' => 'button',
			]));
			$form->addHtml(Str::html('input', [
				'type'  => 'hidden',
				'name'  => 'poll',
				'value' => $poll['id'],
			]));
			$form->addHtml(Str::html('input', [
				'type'  => 'hidden',
				'name'  => Utils::$context['session_var'],
				'value' => Utils::$context['session_id'],
			]));

			echo $form;
		} else {
			$div = Str::html('div');
			$div->addHtml(Str::html('strong')->addHtml(Str::html('a', [
				'class' => 'bbc_link',
				'href'  => Config::$scripturl . '?topic=' . $poll['topic'] . '.0',
			])->setText($poll['question'])));

			$dl = Str::html('dl', ['class' => 'stats']);
			foreach ($poll['options'] as $option) {
				$dt = Str::html('dt')->setText($option['option']);
				$dd = Str::html('dd', ['class' => 'statsbar generic_bar righttext']);

				if ($poll['allow_view_results']) {
					$bar = Str::html('div', [
						'class' => 'bar' . (empty($option['percent']) ? ' empty' : ''),
						'style' => empty($option['percent']) ? '' : 'width: ' . $option['percent'] . '%',
					]);

					$dd->addHtml($bar);
					$dd->addHtml(
						Str::html('span')
							->setText($option['votes'] . ' (' . $option['percent'] . '%)')
					);
				}

				$dl->addHtml($dt)->addHtml($dd);
			}

			$div->addHtml($dl);
			if ($poll['allow_view_results']) {
				$div->addHtml(
					Str::html('strong')
						->setText(Lang::$txt['poll_total_voters'] . ': ' . $poll['total_votes'])
				);
			}

			echo $div;
		}
	}

	private function getAll(): array
	{
		$select = $this->sql->select()
			->from(['t' => 'topics'])
			->columns(['id_topic'])
			->join(['p' => 'polls'], 'p.id_poll = t.id_poll', ['question'])
			->join(['b' => 'boards'], 'b.id_board = t.id_board')
			->where(['t.approved' => 1]);

		$result = $this->sql->execute($select);

		$polls = [];
		foreach ($result as $row) {
			$polls[$row['id_topic']] = $row['question'];
		}

		return $polls;
	}
}
